class Solution {
public:
    int tmp[500001];
    int reversePairs(vector<int>& record) {
        return MergeSort(record, 0, record.size() - 1);
    }

    int MergeSort(vector<int>& nums, int left, int right)
    {
        if (left >= right) return 0;

        int mid = left + (right - left) / 2;
        int ret = 0;
        ret += MergeSort(nums, left, mid);
        ret += MergeSort(nums, mid + 1, right);

        int cur1 = left, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= right)
        {
            if (nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1];
                cur1++;
            }
            else {
                tmp[i++] = nums[cur2];
                ret += mid - cur1 + 1;
                cur2++;
            }
        }

        while (cur1 <= mid) tmp[i++] = nums[cur1++];
        while (cur2 <= right) tmp[i++] = nums[cur2++];
        for (int k = left; k <= right; k++)
            nums[k] = tmp[k - left];

        return ret;
    }
};